package com.xuexi.leetcode;

import com.xuexi.yilai.ListNode;

/**
 * @Author: 梁二东
 * @Date: 2024/11/27 10:43
 * @Description: 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 **/
public class RemoveNthFromEnd {

    public static void main(String[] args) {
        RemoveNthFromEnd removeNthFromEnd = new RemoveNthFromEnd();
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(3);
        l1.next.next.next = new ListNode(4);
        l1.next.next.next.next = new ListNode(5);

//        ListNode listNode = removeNthFromEnd.removeNthFromEnd(l1, 2);
//        System.out.println(listNode);

        ListNode listNode2 = removeNthFromEnd.removeNthFromEndDoublePointer(l1, 2);
        System.out.println(listNode2);
    }

    /**
     * 双指针解法
     *
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEndDoublePointer(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode first = head;
        ListNode second = dummy;
        for (int i = 0; i < n; ++i) {
            first = first.next;
        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        ListNode ans = dummy.next;
        return ans;
    }

    /**
     * 普通解法
     *
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode curr = head;
        int i = 0;
        while (curr != null) {
            curr = curr.next;
            i++;
        }
        if (i < n) {
            return new ListNode(0);
        }
        ListNode dummy = new ListNode(0, head);
        ListNode curr2 = dummy;
        int del = i - n + 2;
        while (curr2 != null) {
            if (--del == 1) {
                break;
            }
            curr2 = curr2.next;
        }
        curr2.next = curr2.next.next;
        return dummy.next;
    }

}
